﻿namespace Raven
{
    public class GoalAttackTarget : GoalComposite<RavenBot>
    {
        public GoalAttackTarget(RavenBot owner) : base(owner, GoalType.goal_attack_target)
        {
        }

        public override void Activate()
        {
            _status = GoalStatus.active;

            //if this goal is reactivated then there may be some existing subgoals that
            //must be removed
            RemoveAllSubgoals();

            //it is possible for a bot's target to die whilst this goal is active so we
            //must test to make sure the bot always has an active target
            if (!_owner.GetTargetSys().isTargetPresent())
            {
                _status = GoalStatus.completed;

                return;
            }

            //if the bot is able to shoot the target (there is LOS between bot and
            //target), then select a tactic to follow while shooting
            if (_owner.GetTargetSys().isTargetShootable())
            {
                //if the bot has space to strafe then do so
                Vector2 dummy = Vector2.zero;
                if (_owner.CanStepLeft(ref dummy) || _owner.CanStepRight(ref dummy))
                {
                    AddSubgoal(new GoalDodgeSideToSide(_owner));
                }

                //if not able to strafe, head directly at the target's position 
                else
                {
                    AddSubgoal(new GoalSeekToPosition(_owner, _owner.GetTargetBot().Pos()));
                }
            }

            //if the target is not visible, go hunt it.
            else
            {
                AddSubgoal(new GoalHuntTarget(_owner));
            }
        }

        public override GoalStatus Process()
        {
            //if status is inactive, call Activate()
            ActivateIfInactive();
    
            //process the subgoals
            _status = ProcessSubgoals();

            ReactivateIfFailed();

            return _status;
        }

        public override void Terminate()
        {
            _status = GoalStatus.completed;
        }
    }
}